﻿ko.bindingHandlers.scroll = {
    updating: true,

    init: function(element, valueAccessor, allBindingsAccessor) {
        var self = this;
        self.updating = true;
        ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
            $(window).off("scroll.ko.scrollHandler");
            self.updating = false;
        });
    },

    update: function(element, valueAccessor, allBindingsAccessor) {
        var props = allBindingsAccessor().scrollOptions;
        var offset = props.offset ? props.offset : "0";
        var loadFunc = props.loadFunc;
        var load = ko.utils.unwrapObservable(valueAccessor());
        var self = this;

        if (load) {
            element.style.display = "";
            $(window).on("scroll.ko.scrollHandler", function() {
                var dH = $(document).height();
                var wH = $(window).height();
                var wS = $(window).scrollTop();
                var heightScroll = (dH - offset <= wH + wS);
                if (heightScroll) {
                    if (self.updating) {
                        loadFunc();
                        self.updating = false;
                    }
                } else {
                    self.updating = true;
                }
            });
        } else {
            element.style.display = "none";
            $(window).off("scroll.ko.scrollHandler");
            self.updating = false;
        }
    }
};


ko.bindingHandlers.fadeVisible = {
    init: function (element, valueAccessor) {
        var value = valueAccessor();
        $(element).toggle(ko.unwrap(value)); // Use "unwrapObservable" so we can handle values that may or may not be observable
    },
    update: function (element, valueAccessor) {
        var value = valueAccessor();
        ko.unwrap(value) ? $(element).fadeIn(100) : $(element).fadeOut(100);
    }
};

ko.bindingHandlers.fadeVisible = {
    update: function (element, valueAccessor, allBindings) {
        $(window).keydown(function (eventObject) {
            if (eventObject.which == 27)
                $(element).hide();
        });
    }
};